/**
 * index page
 */
(function () {

  //setHTML 
  function setHTML() {
    let baseVal = 100;
    let pageWidth = 375;
    let maxFontSize = 200;
    let screenWidth = document.querySelector("html").offsetWidth;
    let fontsize = (screenWidth * baseVal) / pageWidth;
    if (fontsize > maxFontSize) {
      fontsize = maxFontSize;
    }
    document.querySelector("html").style.fontSize = fontsize + "px";
  }

  // events
  var actions = {
    toggleSider: function () {

      var user = document.querySelector('#userIcon');
      var siderbar = document.querySelector('#siderbar');
      var siderCover = document.querySelector('#siderCover');

      if (!user){
        return
      }

      user.addEventListener('click', function () {
        if (siderbar.classList.value.indexOf('active') > -1) {
          siderCover.classList.remove('active')
          siderbar.classList.remove('active')
        } else {
          siderCover.classList.add('active')
          siderbar.classList.add('active')
        }
      })

      siderCover.addEventListener('click', function (e) {
        siderCover.classList.remove('active')
        siderbar.classList.remove('active')
      }, true)
    },

    initIndexSwipe: function () {
      var bannerWrap = document.querySelector('#bannerWrap')
      if (!bannerWrap){
        return
      }
      var children = bannerWrap.children
      var len = bannerWrap.childElementCount;
      bannerWrap.style.width = 100 * len + '%'
      for (var c of children) {
        c.style.width = 100 / len + '%'
      }

      var num = 0
      var timer = null
      var orginX = 0
      var itemLength = 100 / len
      
      function run(n) {
        if (num >= (100 * (len - 1) / len)){
          num = 0
        } else {
          num += itemLength
        }
        bannerWrap.style.transform = 'translate3d(-' + num + '%,0,0)';
      }

      function moveNext(n) {
        bannerWrap.style.transform = 'translate3d(-' + (n * itemLength + num) + '%,0,0)';
        timer = setInterval(run, 3000);
      }

      bannerWrap.addEventListener('touchstart', function(e) {
        clearInterval(timer)
        orginX=e.touches[0].pageX;
      })

      bannerWrap.addEventListener('touchmove', function(e) {
        var _x = e.touches[0].pageX;
      })

      bannerWrap.addEventListener('touchend', function(e) {
        var _x = e.changedTouches[0].pageX
        console.log(_x-orginX)
        if (_x - orginX >= 10) {
          // ->
          moveNext(1)
        } else if (_x - orginX <= -10){
          // <-
          moveNext(-1)
        }
      })




      // start animate
      timer = setInterval(run, 3000);
    }

  }



  // init
  window.onload = function () {
    actions.initIndexSwipe()
    actions.toggleSider()
  }


})();